package com.elm_springboot_s.controller;

import com.elm_springboot_s.pojo.Cart;
import com.elm_springboot_s.pojo.RespondMessage;
import com.elm_springboot_s.service.CartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/cart")
@Api(tags = "购物车相关接口")
public class CartController {

    @Autowired
    private CartService cartService;

    @GetMapping("/listCart")
    @ApiOperation("查询购物车信息")
    public RespondMessage<List<Cart>> listCart(Long userId, Integer businessId) {
        try {
            List<Cart> carts;
            if (businessId != null) {
                carts = cartService.listCartByUserIdAndBusinessId(userId, businessId);
            } else {
                carts = cartService.listCartByUserId(userId);
            }
            return RespondMessage.success(carts);
        } catch (Exception e) {
            return RespondMessage.error("查询购物车失败：" + e.getMessage());
        }
    }

    @PostMapping("/saveCart")
    @ApiOperation("添加购物车")
    public RespondMessage<Integer> saveCart(Long userId, Integer businessId, Integer foodId) {
        try {
            int result = cartService.saveCart(userId, businessId, foodId);
            return RespondMessage.success(result);
        } catch (Exception e) {
            return RespondMessage.error("添加购物车失败：" + e.getMessage());
        }
    }

    @PutMapping("/updateCart")
    @ApiOperation("更新购物车")
    public RespondMessage<Integer> updateCart(Long userId, Integer businessId, 
                                            Integer foodId, Integer quantity) {
        try {
            int result = cartService.updateCart(userId, businessId, foodId, quantity);
            return RespondMessage.success(result);
        } catch (Exception e) {
            return RespondMessage.error("更新购物车失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/removeCart")
    @ApiOperation("删除购物车")
    public RespondMessage<Integer> removeCart(Long userId, Integer businessId, Integer foodId) {
        try {
            int result;
            if (foodId != null) {
                result = cartService.removeCart(userId, businessId, foodId);
            } else {
                result = cartService.removeCartByUserIdAndBusinessId(userId, businessId);
            }
            return RespondMessage.success(result);
        } catch (Exception e) {
            return RespondMessage.error("删除购物车失败：" + e.getMessage());
        }
    }
} 